#include "simple_epoll.hpp"
#include "waker.hpp"

namespace mina
{
	IMPL_LOGGER(Waker, logger);

	Waker::Waker()
	{
		_sleeping_flag  = false;

		if (::pipe(_pipe_fds) < 0)
		{
			LOG4CPLUS_ERROR(logger, "pipe error");
			assert(false);

			_pipe_fds[0]  = -1;
			_pipe_fds[1]  = -1;
			return;
		}

		fcntl(_pipe_fds[0], F_SETFL, O_NONBLOCK);
		close(_pipe_fds[1]);
	}

	Waker::~Waker()
	{
		close(_pipe_fds[0]);
	}

	bool Waker::sleep()
	{
		_sleeping_flag  = !_sleeping_flag;
		return _sleeping_flag;
	}

	void Waker::wake(SimpleEpoll & epoll)
	{
		// do nothing
	}

	void Waker::wakeup(SimpleEpoll & epoll)
	{
		epoll.mod(_pipe_fds[0], EPOLLIN | EPOLLET, (void*)NULL);
	}
}

